#include "devicecommservice.h"
#include <QCoreApplication>
#include <QDebug>
#include <QTimer>
#include <QThread>
#include <TaskManager.h>

DeviceCommService::DeviceCommService(QObject* parent)
    : QObject(parent)
    , m_deviceController(DeviceController::instance())
    , m_connected(false)
    , m_currentGroupIndex(-1)
    , m_totalGroups(0)
    , m_autoMode(false)
    , m_isGroupExecuting(false)
    , m_currentCommandIndex(0)
    , m_currentGroupType(MotionGroup) // 默认移动组
{
    m_autoConnectTimer = new QTimer(this);
    m_autoConnectTimer->setSingleShot(true);
    connect(m_autoConnectTimer, &QTimer::timeout, this, &DeviceCommService::onAutoConnectTimeout);

    // 新增执行监控定时器
    m_executionMonitorTimer = new QTimer(this);
    connect(m_executionMonitorTimer, &QTimer::timeout, this, &DeviceCommService::checkGroupExecutionStatus);

    m_deviceController->initialize();
    setupConnections();
    autoConnectToDevice();
}

DeviceCommService::~DeviceCommService()
{
    if (m_autoConnectTimer) {
        m_autoConnectTimer->stop();
        delete m_autoConnectTimer;
    }
    if (m_executionMonitorTimer) {
        m_executionMonitorTimer->stop();
        delete m_executionMonitorTimer;
    }
}

void DeviceCommService::setupConnections()
{
    connect(m_deviceController, &DeviceController::connected,
            this, &DeviceCommService::onDeviceConnected);
    connect(m_deviceController, &DeviceController::disconnected,
            this, &DeviceCommService::onDeviceDisconnected);
    connect(m_deviceController, &DeviceController::errorOccurred,
            this, &DeviceCommService::onDeviceErrorOccurred);
    connect(m_deviceController, &DeviceController::commandResponseReceived,
            this, &DeviceCommService::onCommandResponseReceived);
    connect(m_deviceController, &DeviceController::commandDataResponseReceived,
            this, &DeviceCommService::onCommandDataResponseReceived);

    // 连接立即查询数据信号
    connect(m_deviceController, &DeviceController::queryDataReceived,
            this, &DeviceCommService::onQueryDataReceived);
}

// 处理立即查询数据
void DeviceCommService::onQueryDataReceived(DeviceProtocol::IPCCommand command, const QVariantMap &data)
{
    handleQueryData(command, data);
}

void DeviceCommService::autoConnectToDevice()
{
    log("设备通信服务初始化完成，正在自动连接设备...");
    m_autoConnectTimer->start(1500);
}

void DeviceCommService::onAutoConnectTimeout()
{
    connectToDevice("127.0.0.1", 9600);
}

void DeviceCommService::onGroupExecutionFinished()
{
    stopGroupExecutionMonitoring();
    m_isGroupExecuting = false;
    m_timeoutCount = 0;

    // 如果是气缸组执行完成，更新初始状态为当前状态
    if (m_currentGroupType == CylinderGroup && !m_statusTable.fixtureStatus.isEmpty()) {
        m_initialFixtureStatus = m_statusTable.fixtureStatus;
        log(QString("🔄 更新初始气缸状态为: %1").arg(m_initialFixtureStatus));
    }

    if (!m_autoMode) return;

    log(QString("✅ 第 %1 组指令执行完成").arg(m_currentGroupIndex + 1));

    // 发出执行完成信号
    emit groupExecutionFinished(m_currentGroupIndex);

    // 更新进度
    int progress = ((m_currentGroupIndex + 1) * 100) / m_totalGroups;
    emit autoExecutionProgress(m_currentGroupIndex + 1, m_totalGroups,
                               QString("第 %1 组完成").arg(m_currentGroupIndex + 1));

    // 检查是否所有组都完成
    if (!hasMoreGroups()) {
        TaskManager::instance().completeTaskStatus(TaskType::RUN_START,true,"所有指令组执行完成");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::SpindleStop);

        // 发送自动执行完成信号
        emit autoExecutionFinished(true, "所有指令组执行完成");
        m_autoMode = false;  // 关闭自动模式
    } else if (m_autoMode) {
        // 自动模式下：等待设备完全就绪后执行下一组
        log("🔄 等待设备准备下一组指令...");
        QTimer::singleShot(10, this, [this]() {
            if (m_autoMode && (m_statusTable.runStatus == RunStatus::Idle ||
                               m_statusTable.runStatus == RunStatus::Initialized)) {
                clearAndUploadGroup();
            } else {
                QTimer::singleShot(10, this, [this]() {
                    if (m_autoMode) {
                        clearAndUploadGroup();
                    }
                });
            }
        });
    }
}

void DeviceCommService::connectToDevice(const QString& ip, quint16 port)
{
    if (m_connected) {
        log("设备已经连接");
        return;
    }

    log(QString("正在连接设备 %1:%2...").arg(ip).arg(port));
    m_deviceController->connectToDevice(ip, port);
}

void DeviceCommService::disconnectFromDevice()
{
    m_deviceController->disconnectFromDevice();
}

void DeviceCommService::setCommands(const QVector<QString> &commands)
{
    m_commands = commands;
    // 如果使用单组模式，将整个指令列表作为一个组
    if (!commands.isEmpty()) {
        m_commandGroups.clear();
        m_commandGroups.append(commands);
        m_totalGroups = 1;
    }
}

void DeviceCommService::setCommandGroups(const QVector<QVector<QString> > &commandGroups)
{
    m_commandGroups = commandGroups;
    m_currentGroupIndex = -1;
    m_totalGroups = commandGroups.size();
    m_isGroupExecuting = false;

    log(QString("接收到 %1 组指令").arg(m_commandGroups.size()));
}

void DeviceCommService::onDeviceConnected()
{
    m_connected = true;
    updateConnectionStatus(true);
    log("✅ 设备连接成功");
    emit deviceConnected();
}

void DeviceCommService::onDeviceDisconnected()
{
    m_connected = false;
    updateConnectionStatus(false);
    log("设备断开连接");
    emit deviceDisconnected();
}

void DeviceCommService::onDeviceErrorOccurred(const QString& error)
{
    log("设备错误: " + error);
    emit deviceErrorOccurred(error);
}

void DeviceCommService::onCommandResponseReceived(DeviceProtocol::IPCCommand command, bool success, const QString& message)
{
    QString cmdName;
    switch (command) {
    case DeviceProtocol::IPCCommand::DeviceInitialize: cmdName = "设备初始化"; break;
    case DeviceProtocol::IPCCommand::SetupRecipe: cmdName = "设置工艺参数"; break;
    case DeviceProtocol::IPCCommand::QueryRecipe: cmdName = "查询工艺参数"; break;
    case DeviceProtocol::IPCCommand::QueryState: cmdName = "查询设备状态"; break;
    case DeviceProtocol::IPCCommand::PauseHeartBeat: cmdName = "停止状态上传"; break;
    case DeviceProtocol::IPCCommand::QueryActionList: cmdName = "查询动作列表"; break;
    case DeviceProtocol::IPCCommand::RemoveAction: cmdName = "删除动作"; break;
    case DeviceProtocol::IPCCommand::QueryDIList: cmdName = "查询DI状态"; break;
    case DeviceProtocol::IPCCommand::QueryActionChecksum: cmdName = "查询校验和"; break;
    case DeviceProtocol::IPCCommand::FastMotion: cmdName = "快速移动"; break;
    case DeviceProtocol::IPCCommand::FastCutting: cmdName = "快速切割"; break;
    case DeviceProtocol::IPCCommand::AppendSetDO: cmdName = "添加开启设备"; break;
    case DeviceProtocol::IPCCommand::AppendResetDO: cmdName = "添加关闭设备"; break;
    case DeviceProtocol::IPCCommand::Execute: cmdName = "执行动作"; break;
    case DeviceProtocol::IPCCommand::Pause: cmdName = "暂停"; break;
    case DeviceProtocol::IPCCommand::SetDO: cmdName = "开启设备"; break;
    case DeviceProtocol::IPCCommand::ResetDO: cmdName = "关闭设备"; break;
    case DeviceProtocol::IPCCommand::ClampAllFixture: cmdName = "全部夹紧"; break;
    case DeviceProtocol::IPCCommand::ReleaseAllFixture: cmdName = "全部松开"; break;
    case DeviceProtocol::IPCCommand::Stop: cmdName = "停止"; break;
    case DeviceProtocol::IPCCommand::SpindleStart: cmdName = "主轴启动"; break;
    case DeviceProtocol::IPCCommand::SpindleStop: cmdName = "主轴停止"; break;
    default: cmdName = QString("未知命令(%1)").arg(static_cast<int>(command)); break;
    }

    QString status = success ? "成功" : "失败";
    log(QString("[命令] %1: %2 - %3").arg(cmdName).arg(status).arg(message));

    emit commandExecuted(cmdName, success);
}

void DeviceCommService::onCommandDataResponseReceived(DeviceProtocol::IPCCommand command, bool success, const QVariantMap &data)
{
    if (!success) {
        log(QString("查询命令 %1 执行失败").arg(static_cast<int>(command)));
        return;
    }

    qDebug() << "收到查询数据响应:" << static_cast<int>(command) << "数据:" << data;
    handleQueryData(command, data);
}

void DeviceCommService::handleQueryData(DeviceProtocol::IPCCommand command, const QVariantMap& data)
{
    switch (command) {
    case DeviceProtocol::IPCCommand::QueryRecipe:
        log("处理工艺参数查询数据");
        updateRecipeParams(data);
        break;

    case DeviceProtocol::IPCCommand::QueryState:
        log("处理设备状态查询数据");
        updateDeviceStatus(data);
        break;

    case DeviceProtocol::IPCCommand::QueryDIList:
        log("处理DI状态查询数据");
        updateDIStatus(data);
        break;

    default:
        log(QString("未知查询命令类型: %1, 数据: %2").arg(static_cast<int>(command)).arg(QString::fromUtf8(QJsonDocument::fromVariant(data).toJson())));
        break;
    }
}

void DeviceCommService::updateDeviceStatus(const QVariantMap &stateData)
{
    bool changed = false;
    RunStatus oldRunStatus = m_statusTable.runStatus;

    // 更新运行状态和控制模式
    if (stateData.contains("state") && stateData.contains("controlMode")) {
        QString stateStr = stateData["state"].toString();
        QString controlModeStr = stateData["controlMode"].toString();

        // 解析设备状态
        AlarmStatus oldAlarmStatus = m_statusTable.alarmStatus;
        ControlMode oldControlMode = m_statusTable.controlMode;

        if (stateStr == "R") {
            m_statusTable.runStatus = RunStatus::Running;
            m_statusTable.alarmStatus = AlarmStatus::NoAlarm;
        } else if (stateStr == "P") {
            m_statusTable.runStatus = RunStatus::Paused;
            m_statusTable.alarmStatus = AlarmStatus::NoAlarm;
        } else if (stateStr == "A") {
            m_statusTable.alarmStatus = AlarmStatus::HasAlarm;
        } else if (stateStr == "F") {
            m_statusTable.runStatus = RunStatus::Idle;
            m_statusTable.alarmStatus = AlarmStatus::NoAlarm;
        } else if (stateStr == "I") {
            m_statusTable.runStatus = RunStatus::Initialized;
            m_statusTable.alarmStatus = AlarmStatus::NoAlarm;
        }

        // 解析控制模式
        if (controlModeStr == "R") {
            m_statusTable.controlMode = ControlMode::Remote;
        } else if (controlModeStr == "L") {
            m_statusTable.controlMode = ControlMode::Local;
        }

        changed = (oldRunStatus != m_statusTable.runStatus) ||
                  (oldAlarmStatus != m_statusTable.alarmStatus) ||
                  (oldControlMode != m_statusTable.controlMode);

        // 关键修改：在自动模式下，根据状态变化判断执行完成
        if (m_autoMode && m_isGroupExecuting) {
            handleExecutionStateChange(oldRunStatus, m_statusTable.runStatus);
        }
    }

    // 更新主轴转速 x,y,z

    // Coordinate absolutePosition;            // 绝对坐标
    // Coordinate relativePosition;            // 相对坐标
    if (stateData.contains("x")) {m_statusTable.relativePosition.x= stateData["x"].toDouble();}
    if (stateData.contains("y")) {m_statusTable.relativePosition.y= stateData["y"].toDouble();}
    if (stateData.contains("z")) {m_statusTable.relativePosition.z= stateData["z"].toDouble();}
    if (stateData.contains("torque")) {m_statusTable.torque= stateData["torque"].toDouble();}

    if (changed) {
        m_statusTable.updateStatusTime();
        emit statusUpdated(m_statusTable);
        log(QString("设备状态更新: %1 -> %2").arg(getRunStatusText(oldRunStatus), getRunStatusText(m_statusTable.runStatus)));

        // 检查是否快速执行完成
        if (m_autoMode && m_isGroupExecuting) {
            checkForQuickExecution();
        }
    }
}

void DeviceCommService::updateRecipeParams(const QVariantMap &recipeData)
{
    bool changed = false;

    if (recipeData.contains("D")) {
        m_statusTable.toolDiameter = recipeData["D"].toDouble();
        changed = true;
    }
    if (recipeData.contains("S")) {
        m_statusTable.lineSpacing = recipeData["S"].toDouble();
        changed = true;
    }
    if (recipeData.contains("H")) {
        m_statusTable.cuttingDepth = recipeData["H"].toDouble();
        changed = true;
    }
    if (recipeData.contains("V")) {
        m_statusTable.feedSpeed = recipeData["V"].toDouble();
        changed = true;
    }
    if (recipeData.contains("R")) {
        m_statusTable.spindleSpeed = recipeData["R"].toDouble();
        changed = true;
    }

    if (changed) {
        m_statusTable.updateStatusTime();
        emit statusUpdated(m_statusTable);
        log("工艺参数已更新");
    }
}

void DeviceCommService::updateDIStatus(const QVariantMap &diData)
{
    if (diData.contains("IOBits")) {
        QString IOBits = diData["IOBits"].toString();

        // 如果是第一次获取状态且初始状态为空，设置为初始状态
        if (m_initialFixtureStatus.isEmpty() && !IOBits.isEmpty()) {
            m_initialFixtureStatus = IOBits;
        }

        m_statusTable.fixtureStatus = IOBits;

        m_statusTable.updateStatusTime();
        emit statusUpdated(m_statusTable);
        log(QString("DI状态更新: %1").arg(IOBits));
    }
}

void DeviceCommService::updateConnectionStatus(bool connected)
{
    m_statusTable.deviceConnected = connected ? 1 : 0;
    m_statusTable.updateStatusTime();
    emit statusUpdated(m_statusTable);
}

void DeviceCommService::executeAllGroupsAutomatically()
{
    if (!m_connected) {
        log("❌ 设备未连接，无法执行全自动流程");
        return;
    }

    if (m_commandGroups.isEmpty()) {
        log("❌ 没有可执行的指令组");
        return;
    }

    log("🚀 开始全自动执行所有指令组...");

    // 重置状态
    m_currentGroupIndex = -1;
    m_isGroupExecuting = false;
    m_autoMode = true;
    m_totalGroups = m_commandGroups.size();
    m_initialFixtureStatus.clear(); // 清空初始状态

    // 发出开始信号
    emit autoExecutionStarted();
    emit autoExecutionProgress(0, m_totalGroups, "开始全自动执行");

    log(QString("全自动执行: 共 %1 组指令").arg(m_totalGroups));
    m_statusTable.spindleSpeed = 2000;
    m_statusTable.feedSpeed = 20;

    // 查询初始气缸状态
    log("🔍 查询初始气缸状态...");
    queryDIStatus();

    // 延迟后开始流程，确保获取到初始状态
    QTimer::singleShot(500, this, [this]() {
        if (m_autoMode) {
            m_initialFixtureStatus = m_statusTable.fixtureStatus;
            log(QString("✅ 初始气缸状态获取完成: %1").arg(m_initialFixtureStatus));
            // 开始自动流程：清除并上传第一组
            clearAndUploadGroup();
        }
    });
}

void DeviceCommService::stopAutoExecution()
{
    if (m_autoMode) {
        log("🛑 停止全自动执行");
        m_autoMode = false;
        m_isGroupExecuting = false;
        m_timeoutCount = 0; // 重置超时计数器
        stopGroupExecutionMonitoring();

        emit autoExecutionStopped();
    }
}

void DeviceCommService::clearAndUploadGroup()
{
    if (!m_connected || !m_autoMode) {
        log("❌ 设备连接中断或自动模式已停止");
        m_autoMode = false;
        return;
    }

    m_currentGroupIndex++;

    // 检查是否所有组都执行完成
    if (m_currentGroupIndex >= m_totalGroups) {
        m_statusTable.spindleSpeed = 0;
        m_statusTable.feedSpeed = 0;
        m_autoMode = false;
        emit autoExecutionProgress(m_totalGroups, m_totalGroups, "所有组执行完成！");
        log(QString("成功执行 %1 组指令").arg(m_totalGroups));
        return;
    }

    // 更新进度
    int progress = (m_currentGroupIndex * 100) / m_totalGroups;

    log(QString("🧹 清除设备指令，准备第 %1/%2 组 (进度: %3%)...")
            .arg(m_currentGroupIndex + 1)
            .arg(m_totalGroups)
            .arg(progress));

    // 清除现有动作
    clearAction();
    // 清除完成后上传当前组
    if (m_autoMode) {
        uploadNextGroupAuto();
    }

}

void DeviceCommService::uploadNextGroupAuto()
{
    if (!m_connected || !m_autoMode) {
        return;
    }

    const QVector<QString>& currentGroup = m_commandGroups[m_currentGroupIndex];

    // 判断当前组类型：检查组内是否包含气缸指令
    m_currentGroupType = MotionGroup; // 默认移动组
    for (const QString& command : currentGroup) {
        int cn = getCN(command);
        if (cn == 303 || cn == 304) { // 气缸指令
            m_currentGroupType = CylinderGroup;
            break;
        }
    }

    log(QString("📤 上传第 %1/%2 组指令 (%3 条) - 类型: %4")
            .arg(m_currentGroupIndex + 1)
            .arg(m_totalGroups)
            .arg(currentGroup.size())
            .arg(m_currentGroupType == MotionGroup ? "移动组" : "气缸组"));

    emit autoExecutionProgress(m_currentGroupIndex, m_totalGroups,
                               QString("上传第 %1 组指令").arg(m_currentGroupIndex + 1));

    // 重置指令索引 - 每组都从0开始
    m_currentCommandIndex = 0;

    // 上传当前组的所有指令
    for (int i = 0; i < currentGroup.size(); i++) {
        if (!m_autoMode) break; // 检查是否被停止

        const QString& command = currentGroup[i];
        parseCommandParams(command);

        // 显示上传进度
        if (i % 5 == 0 || i == currentGroup.size() - 1) {
            log(QString("  上传进度: %1/%2").arg(i + 1).arg(currentGroup.size()));
        }
    }

    if (!m_autoMode) return;

    // log(QString("✅ 第 %1 组指令上传完成").arg(m_currentGroupIndex + 1));

    // 开始执行动作组
    if (m_autoMode) {
        startGroupExecutionAuto();
    }

}

void DeviceCommService::startGroupExecutionAuto()
{
    if (!m_connected || !m_autoMode) {
        return;
    }

    // 重置状态
    m_timeoutCount = 0;
    m_executionStartTime = QDateTime::currentDateTime();

    // 先查询一次当前状态，确保设备就绪
    queryDeviceState();

    // 如果是气缸组，额外查询DI状态
    if (m_currentGroupType == CylinderGroup) {
        queryDIStatus();
    }

    log(QString("▶️ 准备执行第 %1 组指令，类型: %2，检查设备状态...")
            .arg(m_currentGroupIndex + 1)
            .arg(m_currentGroupType == MotionGroup ? "移动组" : "气缸组"));

    // 延迟后发送执行命令，确保状态查询完成
    QTimer::singleShot(100, this, [this]() {
        if (!m_autoMode) return;

        // 对于气缸组，检查初始DI状态
        if (m_currentGroupType == CylinderGroup) {
            if (m_statusTable.fixtureStatus.isEmpty()) {
                log("❌ 气缸组初始状态获取失败，停止执行");
                stopAutoExecution();
                return;
            }

            // 记录气缸组执行前的初始状态
            QString groupInitialStatus = m_statusTable.fixtureStatus;
            log(QString("🔍 气缸组执行前状态: %1").arg(groupInitialStatus));
        }

        // 检查设备状态 - 设备处于空闲或初始化完成状态都可以执行
        if ((m_statusTable.runStatus == RunStatus::Idle || m_statusTable.runStatus == RunStatus::Initialized) &&
            m_statusTable.alarmStatus == AlarmStatus::NoAlarm) {

            // 设备就绪，发送执行命令
            m_deviceController->sendCommand(DeviceProtocol::IPCCommand::Execute);
            m_isGroupExecuting = true;

            log(QString("🎯 开始执行第 %1 组指令...").arg(m_currentGroupIndex + 1));

            emit autoExecutionProgress(m_currentGroupIndex, m_totalGroups,
                                       QString("执行第 %1 组指令").arg(m_currentGroupIndex + 1));

            // 开始监控执行状态
            startGroupExecutionMonitoring();

        } else {
            // 设备不空闲，延迟后重试
            log(QString("⚠️ 设备未就绪，当前状态: %1，%2秒后重试")
                    .arg(m_statusTable.toString())
                    .arg(2));

            QTimer::singleShot(2000, this, [this]() {
                if (m_autoMode) {
                    startGroupExecutionAuto(); // 重试
                }
            });
        }
    });
}

void DeviceCommService::checkGroupExecutionStatus()
{
    if (!m_connected || !m_isGroupExecuting) {
        return;
    }

    // 超时检查
    m_timeoutCount++;

    // 先查询状态
    queryDeviceState();

    // 对于气缸组，额外查询DI状态
    if (m_currentGroupType == CylinderGroup) {
        queryDIStatus();
    }

    // 根据组类型进行不同的完成判断
    if (m_currentGroupType == MotionGroup) {
        checkMotionGroupCompletion();
    } else {
        if (!checkCylinderGroupCompletion()) {
            log("❌ 气缸组状态异常，停止自动执行");
            stopAutoExecution();
            emit deviceErrorOccurred("气缸组状态异常，请检查设备");
            return;
        }
    }

    // 完成判断后再检查超时
    int timeoutLimit;
    if (m_currentGroupType == CylinderGroup) {
        timeoutLimit = 3; // 气缸组3秒超时（给设备足够的响应时间）
    } else {
        timeoutLimit = (m_timeoutCount <= 3) ? MAX_TIMEOUT_CHECKS + 60 : MAX_TIMEOUT_CHECKS;
    }

    if (m_timeoutCount > timeoutLimit) {
        if (m_currentGroupType == CylinderGroup) {
            log(QString("❌ 气缸组执行超时，状态未从 %1 变化").arg(m_initialFixtureStatus));
            stopAutoExecution();
            emit deviceErrorOccurred("气缸组执行超时，状态未变化");
        } else {
            log(QString("⚠️ 第 %1 组执行超时，强制进入下一组").arg(m_currentGroupIndex + 1));
            m_timeoutCount = 0;
            onGroupExecutionFinished();
        }
        return;
    }
}

void DeviceCommService::checkMotionGroupCompletion()
{
    // 移动组完成检查逻辑
    if (!m_autoMode || !m_isGroupExecuting) {
        return;
    }

    // 情况1：设备处于报警状态，立即停止
    if (m_statusTable.alarmStatus == AlarmStatus::HasAlarm) {
        log("❌ 移动组执行中检测到设备报警，停止自动执行");
        stopAutoExecution();
        emit deviceErrorOccurred("设备报警，请检查设备状态");
        return;
    }

    // 情况2：检查执行时间，避免长时间运行
    qint64 elapsedSeconds = m_executionStartTime.secsTo(QDateTime::currentDateTime());

    // 根据指令数量估算最大执行时间（假设每条指令平均5秒）
    int estimatedMaxTime = m_commandGroups[m_currentGroupIndex].size() * 5 + 30; // 额外30秒缓冲

    if (elapsedSeconds > estimatedMaxTime) {
        log(QString("❌ 移动组执行超时（已执行%1秒，预估最大%2秒），停止自动执行")
                .arg(elapsedSeconds)
                .arg(estimatedMaxTime));
        stopAutoExecution();
        emit deviceErrorOccurred("移动组执行超时，请检查设备状态");
        return;
    }

    // 情况3：检查设备运行状态
    RunStatus currentStatus = m_statusTable.runStatus;

    // 如果设备处于空闲或初始化状态，并且已经执行了2秒，认为完成
    if ((currentStatus == RunStatus::Idle || currentStatus == RunStatus::Initialized) &&
        elapsedSeconds > 2) { //

        // 额外检查：确保不是刚开始执行就变成空闲的异常情况
        if (m_timeoutCount >= 2) { // 至少检查了2次
            log(QString("✅ 移动组执行完成（设备空闲，已执行%1秒）").arg(elapsedSeconds));
            QTimer::singleShot(500, this, &DeviceCommService::onGroupExecutionFinished);
            return;
        }
    }

    // 情况4：检查坐标位置变化（可选，如果需要更精确的判断）
    // 如果坐标在一定时间内没有变化，可能执行完成或卡住
    static Coordinate lastPosition;
    static int noMovementCount = 0;

    Coordinate currentPosition = m_statusTable.relativePosition;

    // 计算位置变化（简单的欧几里得距离）
    double positionChange = sqrt(pow(currentPosition.x - lastPosition.x, 2) +
                                 pow(currentPosition.y - lastPosition.y, 2) +
                                 pow(currentPosition.z - lastPosition.z, 2));

    if (positionChange < 0.1) { // 位置变化小于0.1mm认为没有移动
        noMovementCount++;
    } else {
        noMovementCount = 0;
        lastPosition = currentPosition;
    }

    // 如果20秒内没有移动，并且设备状态不是运行中，认为可能完成
    if (noMovementCount >= 20 && currentStatus != RunStatus::Running) {
        log("✅ 移动组执行完成（坐标位置稳定）");
        QTimer::singleShot(500, this, &DeviceCommService::onGroupExecutionFinished);
        return;
    }

    // 记录执行状态（每10次检查记录一次，避免日志过多）
    if (m_timeoutCount % 10 == 0) {
        log(QString("移动组执行中... 已执行%1秒，当前位置(X:%2, Y:%3, Z:%4)，状态:%5")
                .arg(elapsedSeconds)
                .arg(currentPosition.x, 0, 'f', 2)
                .arg(currentPosition.y, 0, 'f', 2)
                .arg(currentPosition.z, 0, 'f', 2)
                .arg(getRunStatusText(currentStatus)));
    }
}

bool DeviceCommService::checkCylinderGroupCompletion()
{
    // 检查气缸状态是否有效
    if (m_statusTable.fixtureStatus.isEmpty()) {
        log("⚠️ 气缸状态异常：状态为空");
        return false;
    }

    // 检查是否有报警状态
    if (m_statusTable.alarmStatus == AlarmStatus::HasAlarm) {
        log("❌ 设备报警状态，气缸组执行失败");
        return false;
    }

    QString currentStatus = m_statusTable.fixtureStatus;

    // 气缸组完成条件：只要状态发生变化就立即完成
    if (currentStatus != m_initialFixtureStatus) {
        log(QString("✅ 气缸组执行完成，状态从 %1 变为 %2")
                .arg(m_initialFixtureStatus)
                .arg(currentStatus));
        QTimer::singleShot(100, this, &DeviceCommService::onGroupExecutionFinished);
        return true;
    }

    // 第一次检查时记录状态
    if (m_timeoutCount == 1) {
        log(QString("气缸组开始执行，等待状态变化... 初始状态: %1")
                .arg(m_initialFixtureStatus));
    } else {
        log(QString("气缸组执行中... 当前状态: %1 (等待变化)")
                .arg(currentStatus));
    }

    return true;
}

void DeviceCommService::startGroupExecutionMonitoring()
{
    // 每1秒检查一次执行状态
    m_executionMonitorTimer->start(1000);
    log("开始监控指令执行状态");
}

void DeviceCommService::stopGroupExecutionMonitoring()
{
    if (m_executionMonitorTimer && m_executionMonitorTimer->isActive()) {
        m_executionMonitorTimer->stop();
    }
    m_isGroupExecuting = false;
    log("停止监控指令执行状态");
}

bool DeviceCommService::hasMoreGroups() const
{
    return m_currentGroupIndex < m_totalGroups - 1;
}

void DeviceCommService::uploadAllCommands()
{
    if (!m_connected) {
        logMessage("设备未连接，无法上传指令");
        return;
    }

    if (m_commands.isEmpty()) {
        logMessage("没有可上传的指令，请先生成路径规划");
        return;
    }
    // 记录初始指令数量
    int totalCommands = m_commands.size();
    int uploadedCount = 0;

    log(QString("开始上传路径，共 %1 条指令").arg(totalCommands));

    // 循环上传所有指令
    while (!m_commands.isEmpty()) {
        QString command = m_commands.first();
        uploadedCount++;

        log(QString("上传指令 %1/%2: %3")
                .arg(uploadedCount)
                .arg(totalCommands)
                .arg(command));

        // 上传指令
        parseCommandParams(command);

        // 删除已上传的指令
        m_commands.removeFirst();
    }

    log("✅ 所有指令上传完成");
    log(QString("共上传 %1 条指令").arg(totalCommands));
}

void DeviceCommService::startExecute()
{
    if (!m_connected) {
        log("设备未连接，无法执行指令");
        return;
    }
    // 发送执行命令
    m_deviceController->sendCommand(DeviceProtocol::IPCCommand::Execute);

    log("✅ 执行命令已发送，设备开始执行所有指令");
}

void DeviceCommService::stopExecution()
{
    // 实现停止执行逻辑
}

void DeviceCommService::parseCommandParams(const QString& command)
{
    int cn = getCN(command);

    if (cn == 210 || cn == 211) {
        // 使用统一的参数名
        QVariantMap motionParams = getMotionParams(command);

        DeviceProtocol::IPCCommand motionCommand = (cn == 210)
                                                       ? DeviceProtocol::IPCCommand::FastMotion
                                                       : DeviceProtocol::IPCCommand::FastCutting;

        m_deviceController->sendCommand(motionCommand, motionParams);
    }
    else if (cn == 303 || cn == 304) {
        QVariantMap params = getIoBits(command);

        DeviceProtocol::IPCCommand ioCommand = (cn == 303)
                                                   ? DeviceProtocol::IPCCommand::SetDO
                                                   : DeviceProtocol::IPCCommand::ResetDO;

        m_deviceController->sendCommand(ioCommand, params);
    }
    else {
        log(QString("未知指令类型: CN=%1").arg(cn));
    }
}

// 清除现有动作并初始化
void DeviceCommService::clearAction()
{
    if (!m_connected) {
        log("设备未连接，无法清除指令");
        return;
    }
    QVariantMap removeParams;
    removeParams["NO"] = -1;  // -1 表示删除所有动作

    m_deviceController->sendCommand(
        DeviceProtocol::IPCCommand::RemoveAction,
        removeParams
        );

    logMessage("清除所有现有动作");
    m_currentCommandIndex = 0;


    m_deviceController->sendCommand(DeviceProtocol::IPCCommand::DeviceInitialize);
    logMessage("设备初始化");
}

void DeviceCommService::DeviceCommand(DeviceProtocol::IPCCommand command, const QVariantMap &params)
{
    if (!m_connected) {
        log("设备未连接，无法执行命令");
        return;
    }
    QVariantMap removeParams;
    switch (command) {
    case DeviceProtocol::IPCCommand::DeviceInitialize:
        log("执行设备初始化命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::DeviceInitialize);
        break;

    case DeviceProtocol::IPCCommand::SetupRecipe:
        log("执行设置工艺参数命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::SetupRecipe, params);
        break;

    case DeviceProtocol::IPCCommand::QueryRecipe:
        log("执行查询工艺参数命令");
        queryRecipeParams();
        break;

    case DeviceProtocol::IPCCommand::QueryState:
        log("执行查询设备状态命令");
        queryDeviceState();
        break;

    case DeviceProtocol::IPCCommand::PauseHeartBeat:
        log("执行停止状态上传命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::PauseHeartBeat);
        break;

    case DeviceProtocol::IPCCommand::QueryActionList:
        log("执行查询动作列表命令-有问题-已屏蔽");
        // m_deviceController->sendCommand(DeviceProtocol::IPCCommand::QueryActionList);
        break;

    case DeviceProtocol::IPCCommand::RemoveAction:
        log("执行删除所有动作命令");
        removeParams["NO"] = -1;  // -1 表示删除所有动作
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::RemoveAction,removeParams);
        break;

    case DeviceProtocol::IPCCommand::QueryDIList:
        log("执行查询DI状态命令");
        queryDIStatus();
        break;

    case DeviceProtocol::IPCCommand::QueryActionChecksum:
        log("执行查询校验和命令-已屏蔽");
        // m_deviceController->sendCommand(DeviceProtocol::IPCCommand::QueryActionChecksum);
        break;

    case DeviceProtocol::IPCCommand::FastMotion:
        log("执行快速移动命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::FastMotion, params);
        break;

    case DeviceProtocol::IPCCommand::FastCutting:
        log("执行快速切割命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::FastMotion, params);
        break;

    case DeviceProtocol::IPCCommand::AppendSetDO:
        log("执行添加开启设备命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::AppendSetDO, params);
        break;

    case DeviceProtocol::IPCCommand::AppendResetDO:
        log("执行添加关闭设备命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::AppendResetDO, params);
        break;

    case DeviceProtocol::IPCCommand::Execute:
        log("执行动作命令");
        startExecute();
        break;

    case DeviceProtocol::IPCCommand::Pause:
        log("执行暂停命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::Pause);
        break;

    case DeviceProtocol::IPCCommand::SetDO:
        log("执行IO开启设备命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::SetDO, params);
        break;

    case DeviceProtocol::IPCCommand::ResetDO:
        log("执行关闭设备命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::ResetDO, params);
        break;

    case DeviceProtocol::IPCCommand::ClampAllFixture:
        log("执行全部夹紧命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::ClampAllFixture);
        break;

    case DeviceProtocol::IPCCommand::ReleaseAllFixture:
        log("执行全部松开命令");
        m_deviceController->sendCommand(DeviceProtocol::IPCCommand::ReleaseAllFixture);
        break;
    case DeviceProtocol::IPCCommand::Stop:
        log("执行停止命令");
        stopExecution();
        break;

    default:
        log(QString("未知命令类型: %1").arg(static_cast<int>(command)));
        break;
    }
}


void DeviceCommService::RegressionAction()
{
    if (!m_connected) {
        logMessage("设备未连接，无法回归零位");
        return;
    }

    QVariantMap fastMotionParams;
    fastMotionParams["EZ"] = 21.5;
    fastMotionParams["NO"] = 0;
    fastMotionParams["Count"] = 1;
    m_deviceController->sendCommand(DeviceProtocol::IPCCommand::FastMotion, fastMotionParams);

    fastMotionParams["EX"] = 0;
    fastMotionParams["EY"] = 0;
    fastMotionParams["NO"] = 1;
    fastMotionParams["Count"] = 1;
    m_deviceController->sendCommand(DeviceProtocol::IPCCommand::FastMotion, fastMotionParams);

    m_deviceController->sendCommand(DeviceProtocol::IPCCommand::Execute);
}

void DeviceCommService::executeCommandsProcessing()
{
    if (!m_connected) {
        logMessage("❌ 设备未连接，无法执行完整流程");
        return;
    }
    if (m_commands.isEmpty()) {
        log("❌ 路径规划未完成，无法执行完整流程");
        return;
    }
    logMessage("🔄 开始执行完整流程后续步骤...");

    // 步骤1: 清除指令并初始化设备
    clearAction();

    // 短暂延迟确保初始化完成
    QTimer::singleShot(100, this, [this]() {
        // 步骤2: 上传全部路径
        uploadAllCommands();
        // 步骤3: 运行上传的指令
        startExecute();
    });
}

void DeviceCommService::setupRecipeParams(double toolDiameter, double toolSpeed, double lineSpacing, double cuttingDepth, double feedRate)
{
    QVariantMap recipeParams;
    recipeParams["D"] = toolDiameter;
    recipeParams["R"] = toolSpeed;
    recipeParams["S"] = lineSpacing;
    recipeParams["H"] = cuttingDepth;
    recipeParams["V"] = feedRate;

    m_deviceController->sendCommand(DeviceProtocol::IPCCommand::SetupRecipe, recipeParams);
}

void DeviceCommService::queryDeviceState()
{
    if (!m_connected) {
        log("设备未连接，无法查询状态");
        return;
    }
    m_deviceController->sendCommand(DeviceProtocol::IPCCommand::QueryState);
}

void DeviceCommService::queryRecipeParams()
{
    if (!m_connected) {
        log("设备未连接，无法查询工艺参数");
        return;
    }
    m_deviceController->sendCommand(DeviceProtocol::IPCCommand::QueryRecipe);
}

void DeviceCommService::queryDIStatus()
{
    if (!m_connected) {
        log("设备未连接，无法查询DI状态");
        return;
    }
    QVariantMap params;
    params["IOBits"] = "FFFF";
    m_deviceController->sendCommand(DeviceProtocol::IPCCommand::QueryDIList,params);
}

void DeviceCommService::getCurrentStatus(StatusTable &status) const
{
    status = m_statusTable;
}

int DeviceCommService::getCN(const QString& command)
{
    QRegularExpression cnRegex("CN=(\\d+)");
    QRegularExpressionMatch cnMatch = cnRegex.match(command);

    if (cnMatch.hasMatch()) {
        return cnMatch.captured(1).toInt();
    }
    return -1;
}

QVariantMap DeviceCommService::getMotionParams(const QString& command)
{
    QVariantMap motionParams;

    // 解析所有坐标参数
    QRegularExpression coordRegex("(SX|SY|SZ|EX|EY|EZ)=([-+]?\\d+\\.?\\d*)");
    QRegularExpressionMatchIterator matchIterator = coordRegex.globalMatch(command);

    while (matchIterator.hasNext()) {
        QRegularExpressionMatch match = matchIterator.next();
        QString key = match.captured(1);
        double value = match.captured(2).toDouble();
        motionParams[key] = value;
    }

    // 解析速度和转速参数
    QRegularExpression speedRegex("(V|R)=([-+]?\\d+\\.?\\d*)");
    matchIterator = speedRegex.globalMatch(command);
    while (matchIterator.hasNext()) {
        QRegularExpressionMatch match = matchIterator.next();
        QString key = match.captured(1);
        double value = match.captured(2).toDouble();
        motionParams[key] = value;
    }

    // 设置动作编号和计数
    motionParams["NO"] = m_currentCommandIndex;
    motionParams["Count"] = 1;
    m_currentCommandIndex++;

    return motionParams;
}

QVariantMap DeviceCommService::getIoBits(const QString& command)
{
    QVariantMap params;

    // 改进的正则表达式，支持十六进制和十进制格式
    QRegularExpression IOBitsRegex("IOBits=([0-9A-Fa-f]+)");
    QRegularExpressionMatch IOBitsMatch = IOBitsRegex.match(command);

    if (IOBitsMatch.hasMatch()) {
        QString ioBits = IOBitsMatch.captured(1);

        // 确保IOBits是5位十六进制格式
        bool ok;
        int decimalValue = ioBits.toInt(&ok, 16); // 先按十六进制解析
        if (!ok) {
            decimalValue = ioBits.toInt(&ok, 10); // 如果失败，按十进制解析
        }

        if (ok) {
            // 转换为5位十六进制字符串，前面补零
            params["IOBits"] = QString("%1").arg(decimalValue, 5, 16, QChar('0')).toUpper();
        } else {
            params["IOBits"] = "00000"; // 解析失败使用默认值
            log("❌ IOBits解析失败，使用默认值: 00000");
        }
    } else {
        params["IOBits"] = "00000"; // 未匹配到使用默认值
        log("❌ 未找到IOBits参数，使用默认值: 00000");
    }

    // 调试日志
    log(QString("解析IOBits参数: %1").arg(params["IOBits"].toString()));

    return params;
}

DeviceCommService::GroupType DeviceCommService::getCurrentGroupType(const QVector<QString> &commands)
{
    for (const QString& command : commands) {
        int cn = getCN(command);
        if (cn == 303 || cn == 304) { // 气缸指令
            return CylinderGroup;
        }
    }
    return MotionGroup;
}

QString DeviceCommService::getConnectionStatus() const
{
    return m_connected ? "已连接" : "未连接";
}

void DeviceCommService::log(const QString& message)
{
    qDebug() << "[DeviceCommService]" << message;
    emit logMessage(message);
}


void DeviceCommService::handleExecutionStateChange(RunStatus oldStatus, RunStatus newStatus)
{
    if (!m_autoMode || !m_isGroupExecuting || m_currentGroupType != MotionGroup) {
        return; // 只处理移动组的状态变化
    }

    // 原有的状态变化判断逻辑，但现在作为辅助判断
    if (oldStatus == RunStatus::Running &&
        (newStatus == RunStatus::Idle || newStatus == RunStatus::Initialized)) {
        log("🔄 检测到设备状态变化（Running → 空闲/初始化完成），将在下次检查中确认完成");
        // 不再立即触发完成，而是在 checkMotionGroupCompletion 中综合判断
    }
    // 情况3：如果设备从其他状态变为 Running，表示开始执行
    else if (oldStatus != RunStatus::Running && newStatus == RunStatus::Running) {
        log("🚀 检测到设备开始执行");
        m_executionStartTime = QDateTime::currentDateTime();
        m_timeoutCount = 0; // 重置超时计数器
    }
    // 情况4：如果设备出现报警，停止自动执行
    else if (m_statusTable.alarmStatus == AlarmStatus::HasAlarm) {
        log("❌ 设备报警，停止自动执行");
        stopAutoExecution();
    }
}

void DeviceCommService::checkForQuickExecution()
{
    if (!m_autoMode || !m_isGroupExecuting || m_currentGroupType != MotionGroup) {
        return; // 只处理移动组的快速执行判断
    }

    // 快速执行判断：如果执行开始后短时间内设备一直处于空闲或初始化完成状态
    if (m_timeoutCount >= 3 &&
        (m_statusTable.runStatus == RunStatus::Idle || m_statusTable.runStatus == RunStatus::Initialized)) {
        qint64 elapsed = m_executionStartTime.msecsTo(QDateTime::currentDateTime());
        if (elapsed < 3000) { // 3秒内就完成了（更严格的判断）
            log("✅ 检测到快速执行完成（短时间内保持空闲/初始化完成状态）");
            // 额外验证：检查组内指令是否都是快速指令
            if (isQuickMotionGroup(m_currentGroupIndex)) {
                onGroupExecutionFinished();
            }
        }
    }
}

// 新增辅助方法：判断是否为快速移动组
bool DeviceCommService::isQuickMotionGroup(int groupIndex)
{
    if (groupIndex < 0 || groupIndex >= m_commandGroups.size()) {
        return false;
    }

    const QVector<QString>& group = m_commandGroups[groupIndex];
    for (const QString& command : group) {
        int cn = getCN(command);
        // 如果是长距离移动或复杂指令，不算快速组
        if (cn == 210 || cn == 211) {
            QVariantMap params = getMotionParams(command);
            // 检查移动距离，如果任何坐标移动超过50mm，不算快速组
            if (qAbs(params["EX"].toDouble()) > 50.0 ||
                qAbs(params["EY"].toDouble()) > 50.0 ||
                qAbs(params["EZ"].toDouble()) > 50.0) {
                return false;
            }
        }
    }
    return true;
}

QString DeviceCommService::getRunStatusText(RunStatus status)
{
    switch (status) {
    case RunStatus::Idle: return "空闲";
    case RunStatus::Initialized: return "已初始化";
    case RunStatus::Running: return "运行中";
    case RunStatus::Paused: return "暂停";
    default: return "未知";
    }
}
